use actix_web::{get, post, web::{Data, Json, Path}, HttpResponse};
use bcrypt::{hash, DEFAULT_COST};

use crate::{base::{errors::AppError, response::ApiResponse, Config, DbPool}, data::dto::auth_dto::{LoginRequest, LoginResponse}, service::role_service::RoleService};
use crate::base::response::FateResult;

/// 获取hash密码接口
///
/// 用于生成系统匹配的hash密码
#[utoipa::path(
    get,
    path = "/api/public/hash_password/{password}",
    params(
        ("password", description = "密码")
    ),
    responses(
        (status = 200, description = "操作成功", body = ApiResponse<String>),
        (status = 400, description = "请求数据验证失败", body = String),
        (status = 500, description = "服务器内部错误", body = String)
    ),
    tag = "公开接口"
)]
#[get("/hash_password/{password}")]
pub async fn hash_password(password: Path<String>) -> FateResult {
    let hash_password = hash(password.into_inner(), DEFAULT_COST).unwrap();
    Ok(ApiResponse::success(hash_password))
}

/// 登录
/// 
/// 用于用户登录系统，验证用户是否有使用权限
#[utoipa::path(
    post,
    path = "/api/public/login",
    request_body = LoginRequest,
    responses(
        (status = 200, description = "操作成功", body = ApiResponse<LoginResponse>),
        (status = 400, description = "请求数据验证失败", body = String),
        (status = 500, description = "服务器内部错误", body = String)
    ),
    tag = "公开接口"
)]
#[post("/login")]
pub async fn login(db_pool: Data<DbPool>, config: Data<Config>, request: Json<LoginRequest>) -> FateResult {
    log::info!("用户登录: {:?}", request);
    let response = RoleService::login(&db_pool, &config, request.into_inner()).await?;
    Ok(ApiResponse::success(response))
}